package com.jinzhi.jzapi.training.controller;

import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.jzapi.utils.CerSynthesisUtil;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.IdCardUtil;
import com.jinzhi.jzweb.utils.ValuesUtil;
import com.jinzhi.jzweb.utils.WithZoreUtil;
import com.jinzhi.sys.domain.UserDO;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jinzhi.api.util.TokenTag.TOKEN_TAG;

@Slf4j
@RestController
@RequestMapping("/jzApi/learns")
public class ApiLearnsController extends BaseController {

    @Autowired
    private ChapterService chapterService;
    @Autowired
    private LearnRecordService learnRecordService;
    @Autowired
    private ChapterLearnsService chapterLearnsService;
    @Autowired
    private CourseLearnsService courseLearnsService;
    @Autowired
    private CoursesService coursesService;
    @Autowired
    private TrainingAnswerSheetService trainingAnswerSheetService;
    @Autowired
    private TrainingPapersService trainingPapersService;
    @Autowired
    private TrainingCertificatesService trainingCertificatesService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private DictService dictService;
    @Autowired
    private CertificateProfileService certificateProfileService;

    /**
     * api小程序端-提交学习记录接口
     *
     * @Description: 培训端提交用户学习记录信息；参数： 验证token，章节id，学习时长，开始时间，结束时间
     * @Param: [token，charpterId, times, startTime, endTime]
     * @return: com.jinzhi.common.utils.ApiResult<?>
     * @Author: kl
     * @Date: 2020-04-23
     */
    @GetMapping("/addLearns")
    @Log("api小程序端-提交学习记录接口")
    @ApiOperation(value = "api小程序端-提交学习记录接口", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    @RequiresAuthentication
    @ApiImplicitParams({@ApiImplicitParam(name = TOKEN_TAG, value = TOKEN_TAG, paramType = "header")})
    public ApiResult<?> addLearns(@RequestHeader(value = TOKEN_TAG, required = false) String token, String chapterId, String times, String startTime, String endTime) {
        //1.根据token获取用户登录数据
        UserDO user = this.getClientUser(token);
        if (null == user) {
            return ApiResult.invalid();
        }
        if (StringUtils.isBlank(chapterId)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(times)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(startTime)) {
            return ApiResult.lack("");//缺少参数
        }

        ChapterDO chapterDO = chapterService.selectById(Long.parseLong(chapterId));
        if (chapterDO != null) {
            CoursesDO coursesDO = coursesService.selectById(chapterDO.getCoursesId());
            LearnRecordDO learnRecordDO = new LearnRecordDO();
            learnRecordDO.setUserId(user.getId());//会员id
            learnRecordDO.setCoursesId(chapterDO.getCoursesId());//课程id
            learnRecordDO.setChapterId(chapterDO.getId());//章节id
            learnRecordDO.setDuration(Long.parseLong(times));//时长
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM

            try {
                Date endDate;
                Date startDate = simpleDateFormat.parse(startTime);
                if (StringUtils.isBlank(endTime)) {
                    endDate = new Date();
                } else {
                    endDate = simpleDateFormat.parse(endTime);
                }
                learnRecordDO.setStartTime(startDate);//开始时间
                learnRecordDO.setEndTime(endDate);//结束时间
            } catch (ParseException e) {
                e.printStackTrace();
            }
            learnRecordDO.setState(0);//默认正常
            boolean bbc = learnRecordService.insert(learnRecordDO);
            if (bbc) {
                boolean chc;
                ChapterLearnsDO chapterLearnsDO = chapterLearnsService.findOneByKv("user_id", user.getId(), "courses_id", chapterDO.getCoursesId(), "chapter_id", chapterDO.getId());
                if (chapterLearnsDO != null) {
                    //章节完成条件为学习时长达到对应章节的最短学习时长；
                    Long totleTime = chapterLearnsDO.getTotalDuration() + Long.parseLong(times);
                    chapterLearnsDO.setTotalDuration(totleTime);//总时长
                    //如果学习时长比章节最短学习时长要长，则直接记录通过；章节最短学习时长单位为分钟，学习时长为秒
                    if ((chapterDO.getMinTime() * 60) < totleTime) {
                        chapterLearnsDO.setState(0);
                    } else {
                        chapterLearnsDO.setState(1);
                    }
                    chc = chapterLearnsService.updateById(chapterLearnsDO);
                } else {
                    ChapterLearnsDO chapterLearnsDO1 = new ChapterLearnsDO();
                    chapterLearnsDO1.setCoursesId(chapterDO.getCoursesId());//课程id
                    chapterLearnsDO1.setChapterId(chapterDO.getId());//章节id
                    chapterLearnsDO1.setUserId(user.getId());//会员id
                    chapterLearnsDO1.setTotalDuration(Long.parseLong(times));//总时长（单位：秒）
                    //如果学习时长比章节最短学习时长要长，则直接记录通过；章节最短学习时长单位为分钟，学习时长为秒
                    if ((chapterDO.getMinTime() * 60) < Long.parseLong(times)) {
                        chapterLearnsDO1.setState(0);
                    } else {
                        chapterLearnsDO1.setState(1);
                    }
                    chc = chapterLearnsService.insert(chapterLearnsDO1);
                }

                if (chc) {
                    boolean bbcd = false;
                    boolean cou;
                    Map map = new HashMap();
                    map.put("userId", user.getId());
                    map.put("coursesId", chapterDO.getCoursesId());
                    Integer selComNum = chapterLearnsService.selComNum(map);
                    CourseLearnsDO courseLearnsDO = courseLearnsService.findOneByKv("user_id", user.getId(), "courses_id", chapterDO.getCoursesId());
                    if (courseLearnsDO != null) {
                        Long totleTimes = courseLearnsDO.getTotalDuration() + Long.parseLong(times);
                        courseLearnsDO.setTotalDuration(totleTimes);//总时长（单位：秒）
                        courseLearnsDO.setCompletionNumber(selComNum);//完成数
                        if (coursesDO.getAdoptFactor().equals("所有章节通过")) {
                            List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", chapterDO.getCoursesId());
                            if (chapterDOS != null && chapterDOS.size() > 0) {
                                if (chapterDOS.size() <= courseLearnsDO.getCompletionNumber()) {
                                    courseLearnsDO.setState(0);
                                    bbcd = true;
                                }
                            } else {
                                courseLearnsDO.setState(0);
                                bbcd = true;
                            }
                        } else if (coursesDO.getAdoptFactor().equals("所有章节通过以及测试达到合格")) {
                            boolean ccdd = true;
                            List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", chapterDO.getCoursesId());
                            if (chapterDOS != null && chapterDOS.size() > 0) {
                                if (chapterDOS.size() > courseLearnsDO.getCompletionNumber()) {
                                    ccdd = false;
                                }
                            }

                            Integer passMark = 1000000;
                            List<TrainingAnswerSheetDO> trainingAnswerSheetDOS = trainingAnswerSheetService.findByKv("user_id", user.getId());
                            if (trainingAnswerSheetDOS != null && trainingAnswerSheetDOS.size() > 0) {
                                for (TrainingAnswerSheetDO trainingAnswerSheetDO : trainingAnswerSheetDOS) {
                                    TrainingPapersDO trainingPapersDO = trainingPapersService.selectById(trainingAnswerSheetDO.getTpapersId());
                                    if (trainingPapersDO != null) {
                                        if (trainingPapersDO.getType().equals(1) && trainingPapersDO.getCoursesId().equals(chapterDO.getCoursesId())) {
                                            passMark = trainingPapersDO.getPassMark();
                                        }
                                    }
                                }
                            }
                            if (courseLearnsDO.getTestScores() == null) {
                                ccdd = false;
                            } else {
                                if (courseLearnsDO.getTestScores() < passMark) {
                                    ccdd = false;
                                }
                            }

                            if (ccdd) {
                                courseLearnsDO.setState(0);
                                bbcd = true;
                            }
                        }
                        cou = courseLearnsService.updateById(courseLearnsDO);
                    } else {
                        CourseLearnsDO courseLearnsDO1 = new CourseLearnsDO();
                        courseLearnsDO1.setCoursesId(chapterDO.getCoursesId());//课程id
                        courseLearnsDO1.setUserId(user.getId());//会员id
                        courseLearnsDO1.setTotalDuration(Long.parseLong(times));//总时长（单位：秒）
                        courseLearnsDO1.setCompletionNumber(selComNum);//完成数
                        courseLearnsDO1.setState(1);//默认未通过

                        if (coursesDO.getAdoptFactor().equals("所有章节通过")) {
                            List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", chapterDO.getCoursesId());
                            if (chapterDOS != null && chapterDOS.size() > 0) {
                                if (chapterDOS.size() <= courseLearnsDO1.getCompletionNumber()) {
                                    courseLearnsDO.setState(0);
                                    bbcd = true;
                                }
                            } else {
                                courseLearnsDO1.setState(0);
                                bbcd = true;
                            }
                        }
                        cou = courseLearnsService.insert(courseLearnsDO1);
                    }

                    if (cou) {
                        if (bbcd) {
                            if (coursesDO != null) {
//                                CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(coursesDO.getProfileId());
//                                if(certificateProfileDO != null){
//                                    String cerName;
//                                    if(certificateProfileDO.getName().length() > 4){
//                                        cerName = certificateProfileDO.getName().substring(0, 4);
//                                    }else{
//                                        cerName = certificateProfileDO.getName();
//                                    }
                                    OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(coursesDO.getOrgId());
                                    if (organizationNewsDO != null) {
                                        //证书图片
                                        String cerImgUrl = null;
                                        String cerImgUrlNoSale = null;

                                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                        String dateNow = sdf.format(new Date());
                                        //具体的年、月、日可利用substring截取
                                        //dateNow.substring(开始下标，结束下标),下标原则：从0开始，包前不包后
                                        String cerYear = dateNow.substring(0, 4);
                                        String cerMath = dateNow.substring(5, 7);
                                        String cerDay = dateNow.substring(8, 10);

                                        String dateNow1 = sdf.format(coursesDO.getCreaterDate());
                                        String traYear = dateNow1.substring(0, 4);
                                        String traMath = dateNow1.substring(5, 7);
                                        String traDay = dateNow1.substring(8, 10);
                                        //获取当前年份后两位
                                        String yearRe = traYear.substring(2,4);

                                        Map mapss = new HashMap();
                                        //获取背景图片
                                        if (coursesDO.getType().equals(1) || coursesDO.getType().equals(3)) {
                                            mapss.put("name", "师资培训证书背景图");
                                            mapss.put("type", "tra_tea_synthesis");
                                        } else if(coursesDO.getType().equals(2) || coursesDO.getType().equals(4)){
                                            mapss.put("name", "考评员培训证书背景图");
                                            mapss.put("type", "tra_exa_synthesis");
                                        }
                                        String traSynthesis = dictService.selDicBy(mapss);
                                        if (StringUtils.isNotBlank(traSynthesis)) {
                                            traSynthesis = ValuesUtil.localUrl + traSynthesis;
                                        }

                                        String electronicSeal = null;
                                        String effectiveDate = null;
                                        if (coursesDO.getType().equals(1) || coursesDO.getType().equals(3)) {
                                            //获取电子公章
                                            mapss.clear();
                                            mapss.put("name", "金职电子公章");
                                            mapss.put("type", "electronic_seal");
                                            electronicSeal = dictService.selDicBy(mapss);
                                            if (StringUtils.isNotBlank(electronicSeal)) {
                                                electronicSeal = ValuesUtil.localUrl + electronicSeal;
                                            }
                                        } else if(coursesDO.getType().equals(2) || coursesDO.getType().equals(4)){
                                            //获取证书有效时长
                                            mapss.clear();
                                            mapss.put("name", "培训证书有效时长");
                                            mapss.put("type", "tra_cer_time");
                                            String traCerTime = dictService.selDicBy(mapss);
                                            if (StringUtils.isNotBlank(traCerTime)) {
                                                //判断是否为数字
                                                if (!IdCardUtil.isNumeric(traCerTime)) {
                                                    return ApiResult.fail("信息错误，请联系管理员！");
                                                }
                                            }else{
                                                traCerTime = "3";
                                            }
                                            String string = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                                            LocalDate today = LocalDate.now();
                                            LocalDate timeDay = today.plus(Integer.parseInt(traCerTime), ChronoUnit.YEARS);
                                            effectiveDate = string + "至" + timeDay;
                                        }

                                        String cerNumbers = "";//证书编号
                                        if (coursesDO.getType().equals(1)) {
                                            cerNumbers = comNumber("JZ", "师资", organizationNewsDO.getProvince(), coursesDO.getName(), yearRe, traMath);
                                        } else if (coursesDO.getType().equals(2)) {
                                            cerNumbers = comNumber("JZ", "考评员", organizationNewsDO.getProvince(), coursesDO.getName(), yearRe, traMath);
                                        } else if (coursesDO.getType().equals(3)) {
                                            cerNumbers = comNumber("JZ", "高级师资", organizationNewsDO.getProvince(), coursesDO.getName(), yearRe, traMath);
                                        } else if (coursesDO.getType().equals(4)) {
                                            cerNumbers = comNumber("JZ", "高级考评员", organizationNewsDO.getProvince(), coursesDO.getName(), yearRe, traMath);
                                        }

                                        if (cerNumbers.contains("填写错误")) {
                                            return ApiResult.fail("课程信息错误，请联系管理员！");
                                        }
                                        int cerEnd = 0;

                                        //查询出该证书编号最大值
                                        String cerNumber = trainingCertificatesService.selCerNumber(cerNumbers);
                                        if (StringUtils.isNotBlank(cerNumber)) {
                                            cerEnd = Integer.parseInt(cerNumber.substring(cerNumber.length() - 4));
                                        }

                                        cerNumbers = cerNumbers + WithZoreUtil.frontCompWithZore(cerEnd + 1, 4);//证书编号

                                        if (coursesDO.getType().equals(1) || coursesDO.getType().equals(3)) {
                                            //师资证书
                                            //查询章节数
                                            List<ChapterDO> chapterDOS = chapterService.findByKv("courses_id", chapterDO.getCoursesId());
                                            try {
                                                String url = user.getHeadPortrait().replace(ValuesUtil.returnUrl, ValuesUtil.localUrl);
                                                //参数说明：合成类型（0带公章，1不带公章），背景图，学员姓名，学员图像， 身份证号码，证书编码，考核期数，培训章节数（学时），培训年份，培训月份，培训日期，获证年份，获证年份，获证年份，电子公章
                                                cerImgUrl = CerSynthesisUtil.overTrainingImage(0, traSynthesis, user.getName(), url, user.getIdNumber(), cerNumbers,
                                                        coursesDO.getName().substring(coursesDO.getName().length() - 4, coursesDO.getName().length() - 2), String.valueOf(chapterDOS.size()),
                                                        traYear, traMath, traDay,cerYear,cerMath,cerDay, electronicSeal,user.getOrgName(),0);
                                                cerImgUrlNoSale = CerSynthesisUtil.overTrainingImage(1, traSynthesis, user.getName(), url, user.getIdNumber(), cerNumbers,
                                                        coursesDO.getName().substring(coursesDO.getName().length() - 4, coursesDO.getName().length() - 2), String.valueOf(chapterDOS.size()),
                                                        traYear, traMath, traDay,cerYear,cerMath,cerDay, electronicSeal,user.getOrgName(),0);
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                        } else if(coursesDO.getType().equals(2) || coursesDO.getType().equals(4)){
                                            //考评员证书
                                            try {
                                                String url = user.getHeadPortrait().replace(ValuesUtil.returnUrl, ValuesUtil.localUrl);
                                                //参数说明：背景图，学员姓名，学员图像， 身份证号码，证书编码，证书名称，有效日期
                                                cerImgUrl = CerSynthesisUtil.overTraExaImage(traSynthesis, user.getName(), url, user.getIdNumber(), cerNumbers, effectiveDate,user.getOrgName(),0);
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                        if(!coursesDO.getType().equals(0)){
                                            //这里新增培训证书信息
                                            TrainingCertificatesDO trainingCertificatesDO = trainingCertificatesService.findOneByKv("user_id", user.getId(), "courses_id", chapterDO.getCoursesId());
                                            if (trainingCertificatesDO == null) {
                                                TrainingCertificatesDO trainingCertificatesDO1 = new TrainingCertificatesDO();
                                                trainingCertificatesDO1.setUserId(user.getId());
                                                trainingCertificatesDO1.setCoursesId(chapterDO.getCoursesId());
                                                trainingCertificatesDO1.setQueries(0);//查询次数
                                                trainingCertificatesDO1.setGetTime(new Date());
                                                trainingCertificatesDO1.setNumbers(cerNumbers);
                                                if (!coursesDO.getType().equals(0)) {
                                                    //转换一下图片路径，将反斜杠替换掉
                                                    String url = cerImgUrl.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
                                                    String imgUrl1 = url.replace("\\", "/");
                                                    trainingCertificatesDO1.setImgUrl(imgUrl1);
                                                    if (coursesDO.getType().equals(1) || coursesDO.getType().equals(3)) {
                                                        String url1 = cerImgUrlNoSale.replace(ValuesUtil.localUrl, ValuesUtil.returnUrl);
                                                        String imgUrl2 = url1.replace("\\", "/");
                                                        trainingCertificatesDO1.setImgUrlNosale(imgUrl2);
                                                    }
                                                }
                                                trainingCertificatesDO1.setState(0);//状态，默认正常
                                                boolean tras = trainingCertificatesService.insert(trainingCertificatesDO1);
                                                if (tras) {
                                                    return ApiResult.success();
                                                } else {
                                                    return ApiResult.build(ApiEnumError.SUMBITERR.getCode(), ApiEnumError.SUMBITERR.getMsg());//提交错误
                                                }
                                            }
                                        }
                                    }else{
                                        return ApiResult.fail("培训机构信息错误，请联系管理员！");
                                    }
//                                }else{
//                                    return ApiResult.fail("证书信息错误，请联系管理员！");
//                                }
                            } else {
                                return ApiResult.fail("课程信息错误，请联系管理员！");
                            }
                        }
                        return ApiResult.success();
                    }
                }
            }
        } else {
            return ApiResult.fail("章节信息错误，请稍后重试！");
        }

        return ApiResult.build(ApiEnumError.SUMBITERR.getCode(), ApiEnumError.SUMBITERR.getMsg());//提交错误
    }


}
